package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebFilter extends ZuulFilter {
   @Override
   public String filterType() {
      return "pre";
   }

   @Override
   public int filterOrder() {
      return 0;
   }

   @Override
   public boolean shouldFilter() {
      return true;
   }
   @Autowired
   private JwtUtil jwtUtil;

   @Override
   public Object run() throws ZuulException {
      //获得RequestContext
      RequestContext requestContext= RequestContext.getCurrentContext();
      //获得原生request对象
      HttpServletRequest request = requestContext.getRequest();
      if(request.getMethod().equals("OPTIONS")){
         //直接放行OPTIONS方式的请求
         return null;
      }
      //提取请求地址
      String url=request.getRequestURL().toString();
      if(url.indexOf("/admin/login")>0){ //判断如果是登录页面=>直接放行,不需要校验管理员权限
         System.out.println("登陆页面"+url);
         return null;
      }
      //获取请求中JWTToken
      String authHeader =(String)request.getHeader("Authorization");//获取头信息
      if(authHeader!=null && authHeader.startsWith("Bearer ") ){//校验token不为空,以及是Bearer 开头
         //提取token
         String token = authHeader.substring(7);
         //解析token=>提取载荷
         Claims claims = jwtUtil.parseToken(token);
         if(claims!=null){
            //提取载荷中的用户角色,并判断是否为管理员
            if("admin".equals(claims.get("role"))){ //是管理员 => 转发请求到微服务,并携带Authorization头
               requestContext.addZuulRequestHeader("Authorization",authHeader);
               System.out.println("token 验证通过，添加了头信息"+authHeader);
               return null;
            }
         }
      }
      //当前用户未登录,或角色不是管理员 => 阻止网关转发
      requestContext.setSendZuulResponse(false);//终止运行
      requestContext.setResponseStatusCode(401);//指定返回响应的状态码
      //为响应添加ContentType头
      requestContext.getResponse().setContentType("text/html;charset=UTF‐8");
      requestContext.setResponseBody("no privilege!"); //指定响应内容

      return null;
   }
}
